package com.educatioin.manage.wechat.service;

import com.educatioin.manage.common.beans.Response;
import com.educatioin.manage.constant.OrderStatus;
import com.educatioin.manage.web.pointreward.po.PointRewardOrderPo;
import com.educatioin.manage.web.pointreward.po.PointRewardProductPo;
import com.educatioin.manage.web.pointreward.repository.PointRewardOrderRepository;
import com.educatioin.manage.web.pointreward.repository.PointRewardProductRepository;
import com.educatioin.manage.web.system.po.CustomerPo;
import com.educatioin.manage.web.system.po.LoginHistoryPo;
import com.educatioin.manage.web.system.repository.CustomerRepository;
import com.educatioin.manage.web.system.repository.LoginHistoryRepository;
import com.educatioin.manage.wechat.dto.PROrderInfoDto;
import com.educatioin.manage.wechat.request.CreatePROrderReq;
import com.educatioin.manage.wechat.response.CreateOrderRsp;
import com.educatioin.manage.wechat.response.QueryPROrdersRsp;
import org.apache.commons.collections.CollectionUtils;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * Created by zhangyin on 2018/5/1.
 */
@Service
public class WeChatPROrderService {

    @Resource
    private PointRewardOrderRepository pointRewardOrderRepository;
    @Resource
    private PointRewardProductRepository pointRewardProductRepository;
    @Resource
    private CustomerRepository customerRepository;
    @Resource
    private LoginHistoryRepository loginHistoryRepository;

    @Transactional
    public QueryPROrdersRsp queryOrdersByToken(HttpServletRequest request){
        QueryPROrdersRsp queryOrdersRsp = new QueryPROrdersRsp();

        Object token = request.getSession().getAttribute("token");
        if(null == token){
            QueryPROrdersRsp queryPROrdersRsp = new QueryPROrdersRsp();
            queryPROrdersRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            queryPROrdersRsp.setReturnMsg("客户未登录！");
            return queryPROrdersRsp;
        }

        //根据token找到已登录用户
        LoginHistoryPo loginHistoryPo = loginHistoryRepository.findByToken(token.toString());
        if(null == loginHistoryPo){
            queryOrdersRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            queryOrdersRsp.setReturnMsg("客户未登录！");
            return queryOrdersRsp;
        }

        String phone = loginHistoryPo.getCustomerName();
        //获取所有订单
        List<PointRewardOrderPo> allOrders = pointRewardOrderRepository.findByPhone(phone);

        List<PROrderInfoDto> alls = Lists.newArrayList();
        List<PROrderInfoDto> pays = Lists.newArrayList();
        List<PROrderInfoDto> deliveries = Lists.newArrayList();
        List<PROrderInfoDto> completes = Lists.newArrayList();

        if(CollectionUtils.isEmpty(allOrders)){
            return queryOrdersRsp;
        }

        for(PointRewardOrderPo pointRewardOrderPo : allOrders){
            PROrderInfoDto orderInfoDto = new PROrderInfoDto();

            orderInfoDto.setOrderCode(pointRewardOrderPo.getOrderCode());
            orderInfoDto.setOrderStatus(OrderStatus.valueOf(pointRewardOrderPo.getOrderStatus()).getDescription());
            orderInfoDto.setPhone(phone);
            orderInfoDto.setAddress(pointRewardOrderPo.getAddress());
            orderInfoDto.setName(pointRewardOrderPo.getName());
            orderInfoDto.setExpressNo(pointRewardOrderPo.getExpressNo()==null?"":pointRewardOrderPo.getExpressNo());
            orderInfoDto.setPrImage(pointRewardOrderPo.getPrImage());
//            StringBuilder sb = new StringBuilder();
//            Map<String,Integer> map = JSON.parseObject(pointRewardOrderPo.getItems(),new TypeReference<Map<String,Integer>>(){});
//            for (Map.Entry<String,Integer> entry:map.entrySet()){
//                PointRewardProductPo pointRewardProductPo = pointRewardProductRepository.findByCode(entry.getKey()).get(0);
//                sb.append(pointRewardProductPo.getName()).append(" * ").append(entry.getValue()).append("\n");
//            }
//            orderInfoDto.setItems(sb.toString());
            orderInfoDto.setTotalPrice(pointRewardOrderPo.getTotalPrice());

            if(OrderStatus.GOODS_SENT.name().equals(pointRewardOrderPo.getOrderStatus())){
                deliveries.add(orderInfoDto);
            }else if(OrderStatus.PAYED.name().equals(pointRewardOrderPo.getOrderStatus())){
                pays.add(orderInfoDto);
            }else if(OrderStatus.COMPLETE.name().equals(pointRewardOrderPo.getOrderStatus())){
                completes.add(orderInfoDto);
            }

            alls.add(orderInfoDto);
        }

        queryOrdersRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        queryOrdersRsp.setAlls(alls);
        queryOrdersRsp.setDeliveries(deliveries);
        queryOrdersRsp.setPays(pays);
        queryOrdersRsp.setCompletes(completes);
        return queryOrdersRsp;
    }

    @Transactional
    public CreateOrderRsp createOrder(HttpServletRequest request, CreatePROrderReq req){
        CreateOrderRsp rsp = new CreateOrderRsp();

        Object token = request.getSession().getAttribute("token");
        if(null == token){
            rsp.setReturnCode(Response.RETURN_FAIL_CODE);
            rsp.setReturnMsg("客户未登录！");
            return rsp;
        }

        LoginHistoryPo loginHistoryPo = loginHistoryRepository.findByToken(token.toString());
        if(null == loginHistoryPo){
            rsp.setReturnCode(Response.RETURN_FAIL_CODE);
            rsp.setReturnMsg("客户未登录！");
            return rsp;
        }

        PointRewardOrderPo pointRewardOrderPo = new PointRewardOrderPo();
        pointRewardOrderPo.setPrProductId(req.getPrProductId());
        pointRewardOrderPo.setAmount(req.getAmount()==null?1:req.getAmount());
        pointRewardOrderPo.setAddress(req.getAddress());
        pointRewardOrderPo.setCustomerName(req.getCustomerName());
//        pointRewardOrderPo.setItems(JSON.toJSONString(req.getItems()));
        pointRewardOrderPo.setPhone(req.getPhone());
        Integer totalPrice = 0;

        //检查库存
//        for (Map.Entry<String,Integer> entry : req.getItems().entrySet()){
//            PointRewardProductPo pointRewardProductPo = pointRewardProductRepository.findByCode(entry.getKey()).get(0);
//            if(0>=pointRewardProductPo.getAmount()) {
//                rsp.setReturnCode(Response.RETURN_FAIL_CODE);
//                rsp.setReturnMsg("商品库存不足！");
//                return rsp;
//            }
//            totalPrice += pointRewardProductPo.getPrice() * entry.getValue();
//        }
        PointRewardProductPo pointRewardProductPo = pointRewardProductRepository.findOne(req.getPrProductId());
        if(0>=pointRewardProductPo.getAmount()) {
                rsp.setReturnCode(Response.RETURN_FAIL_CODE);
                rsp.setReturnMsg("商品库存不足！");
                return rsp;
        }
        pointRewardOrderPo.setName(pointRewardProductPo.getName());
        pointRewardOrderPo.setPrImage(pointRewardProductPo.getShowImage());
        totalPrice += pointRewardProductPo.getPrice() * pointRewardOrderPo.getAmount();
        pointRewardOrderPo.setTotalPrice(totalPrice);

        pointRewardOrderPo.setOrderCode(getOrderCodeByTime());
        pointRewardOrderPo.setOrderStatus(OrderStatus.UN_PAYED.name());
        pointRewardOrderPo.setCreateTime(System.currentTimeMillis());

        pointRewardOrderRepository.save(pointRewardOrderPo);

        rsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        rsp.setOrderCode(pointRewardOrderPo.getOrderCode());
        return rsp;
    }

    public Response payOrder(HttpServletRequest request, String orderCode){
        Response response = new Response();
        PointRewardOrderPo pointRewardOrderPo = pointRewardOrderRepository.findByOrderCode(orderCode);
        if(!Objects.equals(pointRewardOrderPo.getOrderStatus(), OrderStatus.UN_PAYED.name())){
            response.setReturnCode(Response.RETURN_FAIL_CODE);
            response.setReturnMsg("订单已支付");
            return response;
        }

        //根据token找到已登录用户
        Object token = request.getSession().getAttribute("token");
        if(null == token){
            response.setReturnCode(Response.RETURN_FAIL_CODE);
            response.setReturnMsg("客户未登录！");
            return response;
        }

        LoginHistoryPo loginHistoryPo = loginHistoryRepository.findByToken(token.toString());
        if(null == loginHistoryPo){
            response.setReturnCode(Response.RETURN_FAIL_CODE);
            response.setReturnMsg("客户未登录！");
            return response;
        }

        String phone = loginHistoryPo.getCustomerName();
        CustomerPo customerPo = customerRepository.findByPhone(phone);
        Integer point = customerPo.getPoint();
        //判断积分是否足够支付
        if(point<pointRewardOrderPo.getTotalPrice()){
            response.setReturnCode(Response.RETURN_FAIL_CODE);
            response.setReturnMsg("积分余额不足！");
            return response;
        }

//        Map<String,Integer> map = JSON.parseObject(pointRewardOrderPo.getItems(),new TypeReference<Map<String,Integer>>(){});
//
//        //扣库存
//        for (Map.Entry<String,Integer> entry:map.entrySet()){
//            PointRewardProductPo pointRewardProductPo = pointRewardProductRepository.findByCode(entry.getKey()).get(0);
//            pointRewardProductPo.setAmount(pointRewardProductPo.getAmount()-1);
//            pointRewardProductRepository.save(pointRewardProductPo);
//        }
        PointRewardProductPo pointRewardProductPo = pointRewardProductRepository.findOne(pointRewardOrderPo.getPrProductId());
        if(0>=pointRewardProductPo.getAmount()) {
            response.setReturnCode(Response.RETURN_FAIL_CODE);
            response.setReturnMsg("商品库存不足！");
            return response;
        }
        pointRewardProductPo.setAmount(pointRewardProductPo.getAmount()-1);
        pointRewardProductRepository.save(pointRewardProductPo);
        //扣积分
        customerPo.setPoint(point-pointRewardOrderPo.getTotalPrice());
        customerRepository.save(customerPo);

        //更新订单状态
        pointRewardOrderPo.setOrderStatus(OrderStatus.PAYED.name());
        pointRewardOrderRepository.save(pointRewardOrderPo);

        response.setReturnCode(Response.RETURN_SUCCESS_CODE);
        response.setReturnMsg("支付成功！");
        return response;

    }


    private String getOrderCodeByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for(int i = 0; i < 3; i++){
            result += random.nextInt(10);
        }
        return newDate + result;
    }

}
